import { defineStore } from 'pinia'
import { login, logout } from '@/api/auth'
import { getAdminInfo } from '@/api/admin'
import { getShopInfo as getMerchantInfo } from '@/api/merchant'
import { getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => {
    // 安全地解析 localStorage 中的数据
    const getUserInfoFromStorage = () => {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        return userInfoStr ? JSON.parse(userInfoStr) : null
      } catch (error) {
        console.error('解析用户信息失败:', error)
        return null
      }
    }

    const getRolesFromStorage = () => {
      try {
        const rolesStr = localStorage.getItem('roles')
        return rolesStr ? JSON.parse(rolesStr) : []
      } catch (error) {
        console.error('解析角色信息失败:', error)
        return []
      }
    }

    const getPermissionsFromStorage = () => {
      try {
        const permissionsStr = localStorage.getItem('permissions')
        return permissionsStr ? JSON.parse(permissionsStr) : []
      } catch (error) {
        console.error('解析权限信息失败:', error)
        return []
      }
    }

    return {
      token: localStorage.getItem('accessToken') || null,
      refreshToken: localStorage.getItem('refreshToken') || null,
      userInfo: getUserInfoFromStorage(),
      roleType: localStorage.getItem('roleType') || 'admin',
      roles: getRolesFromStorage(),
      permissions: getPermissionsFromStorage()
    }
  },

  getters: {
    isLoggedIn: (state) => !!state.token,
    userName: (state) => state.userInfo?.username || '',
    nickname: (state) => state.userInfo?.nickname || '',
    avatar: (state) => state.userInfo?.avatar || '',
    userRoles: (state) => state.roles,
    userPermissions: (state) => state.permissions,
    roleId: (state) => state.userInfo?.roleId || null,
    isAdmin: (state) => state.userInfo?.roleId === 1,
    isMerchant: (state) => state.userInfo?.roleId === 2
  },

  actions: {
    async login(username, password, roleType) {
      try {
        const response = await login({ username, password })
        
        // 检查响应数据
        if (!response || !response.data) {
          throw new Error('登录响应数据无效')
        }

        const { data } = response
        
        // 获取用户信息对象
        const userData = data.user || data
        
        // 获取用户角色ID
        const userRoleId = userData.roleId || userData.role_id
        if (!userRoleId) {
          throw new Error('登录响应数据中未包含角色信息')
        }

        // 根据后端返回的roleId判断用户类型
        const actualRoleType = userRoleId === 1 ? 'admin' : 'merchant'
        
        // 检查用户选择的登录类型是否匹配
        if (roleType !== actualRoleType) {
          throw new Error('用户角色与选择的登录类型不匹配')
        }

        // 保存 token
        this.setTokens(data.accessToken || data.token, data.refreshToken)
        
        // 构造用户信息，确保必要字段存在
        const userInfo = {
          id: userData.id || userData.adminId || userData.merchantId,
          username: userData.username || username,
          nickname: userData.nickname || username,
          avatar: userData.avatar || '',
          email: userData.email || '',
          phone: userData.phone || '',
          status: userData.status || 1,
          roleId: userRoleId,
          // 商家特有字段
          shopName: userData.shopName || '',
          shopLogo: userData.shopLogo || '',
          shopDesc: userData.shopDesc || '',
          auditStatus: userData.auditStatus || 0,
          address: userData.address || '',
          level: userData.level || 1,
          score: userData.score || 0
        }
        
        // 保存用户信息
        this.setUserInfo(userInfo)
        
        // 设置角色类型
        this.setRoleType(actualRoleType)
        
        // 返回处理后的数据
        return {
          ...data,
          roleId: userRoleId
        }
      } catch (error) {
        console.error('登录失败:', error)
        // 确保清理任何可能已经设置的状态
        this.clearUserInfo()
        throw error
      }
    },

    async fetchUserInfo() {
      try {
        // 1. 获取基础用户信息
        const userResponse = await getUserInfo()
        const userData = userResponse.data
        
        // 2. 如果是商家，获取店铺信息
        let shopData = null
        if (userData.roleId === 2) {
          const shopResponse = await getMerchantInfo()
          shopData = shopResponse.data
        }
        
        // 3. 组合信息
        this.setUserInfo({
          id: userData.id,
          username: userData.username,
          nickname: userData.nickname,
          avatar: userData.avatar,
          email: userData.email,
          phone: userData.phone,
          status: userData.status,
          roleId: userData.roleId,
          // 商家信息作为独立对象
          shop: shopData
        })

        return userData
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },

    async logout() {
      try {
        // 调用统一的登出接口
        await logout()
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 无论请求成功与否，都清除本地信息
        this.clearUserInfo()
      }
    },

    setTokens(accessToken, refreshToken) {
      this.token = accessToken
      this.refreshToken = refreshToken
      localStorage.setItem('accessToken', accessToken)
      localStorage.setItem('refreshToken', refreshToken)
    },

    setUserInfo(info) {
      this.userInfo = info
      localStorage.setItem('userInfo', JSON.stringify(info))
    },

    setRoleType(type) {
      this.roleType = type
      localStorage.setItem('roleType', type)
    },

    clearUserInfo() {
      this.token = null
      this.refreshToken = null
      this.userInfo = null
      this.roles = []
      this.permissions = []
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('roles')
      localStorage.removeItem('permissions')
      localStorage.removeItem('roleType')
    }
  }
}) 